//
// Created by XiaoXiu on 2025/4/29.
//

#include "account.h"
#include <stdio.h>

account *accounts = NULL;

account *create_account(const int id, const char *name, const char *password, const double balance) {
    // 分配 account 结构体内存
    account *new_account = malloc(sizeof(account));
    if (new_account == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return NULL;
    }

    // 设置字段
    new_account->id = id;

    // 安全复制字符串，避免溢出
    strncpy(new_account->name, name, sizeof(new_account->name) - 1);
    new_account->name[sizeof(new_account->name) - 1] = '\0'; // 确保 null 结尾

    strncpy(new_account->password, password, sizeof(new_account->password) - 1);
    new_account->password[sizeof(new_account->password) - 1] = '\0';

    new_account->balance = balance;

    return new_account;
}


void add_account(account *new_account) {
    account *existing = NULL;
    HASH_FIND_INT(accounts, &new_account->id, existing);
    if (existing != NULL) {
        printf("Account with ID %d already exists.\n", new_account->id);  // 注意 ID 是 int
        return;
    }
    HASH_ADD_INT(accounts, id, new_account);  // 使用 new_account->id
}

account *find_account(const int id) {
    account *found = NULL;
    HASH_FIND_INT(accounts, &id, found);
    return found;
}

void delete_account(account *account) {
    if (account == NULL) {
        return;
    }
    HASH_DEL(accounts, account);
    free(account);
}

